<template>
	<view class="edit-userinfo-wrap box relative full">
		<view class="cell-group">
			<view class="cell-item">
				<view class="cell-item-label">
					<text>头像</text>
				</view>
				<view class="cell-content" @click="chooseImage">
					<image :src="userData.avatar" mode="aspectFill" class="avatar" />
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>昵称</text>
				</view>
				<view class="cell-content" @click="toEditDesc('nickname',)">
					<view class="cell-content-text">
						<text>{{ userData.nickname }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>生日</text>
				</view>
				<view class="cell-content" @click="selectBirth">
					<view class="cell-content-text">
						<text>{{ userData.birth || '未设置生日' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>账号</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text">
						<text>{{ userData.sn }}</text>
					</view>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>邀请码</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text" @click="$copy(userData.inviteCode)">
						<text>{{ userData.inviteCode }}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="cell-group">
			<view class="cell-item">
				<view class="cell-item-label">
					<text>手机号</text>
				</view>
				<view class="cell-content" @click="toEditDesc('mobile')">
					<view class="cell-content-text">
						<text>{{ userData.mobile || '未设置' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<!-- <view class="cell-item">
				<view class="cell-item-label">
					<text>性别</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text" @click="showSexPicker = true">
						<text>{{ userData.sex }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view> -->
			<!-- <view class="cell-item">
				<view class="cell-item-label">
					<text>生日</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text" @click="show =  true">
						<text>{{ userData.birthday || '-' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>职业</text>
				</view>
				<view class="cell-content" @click="toEditDesc('job')">
					<view class="cell-content-text">
						<text>{{ userData.career || '-' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
			<view class="cell-item">
				<view class="cell-item-label">
					<text>所在地</text>
				</view>
				<view class="cell-content" @click="showRegin = true">
					<view class="cell-content-text">
						<text>{{ userData.region || '-' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view> -->
			<view class="cell-item">
				<view class="cell-item-label">
					<text>个性签名</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text item-desc" @click="toEditDesc('desc')">
						<text>{{ userData.desc || '-' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
		</view>
		<!-- <view class="cell-group">
			<view class="cell-item">
				<view class="cell-item-label">
					<text>认证</text>
				</view>
				<view class="cell-content">
					<view class="cell-content-text">
						<text>{{ hasAuthorization ? '已认证' : '未认证' }}</text>
					</view>
					<image src="../static/icon/chevron-right.png" class="chevron"></image>
				</view>
			</view>
		</view> -->
		<view class="footer-btn-wrp">
			<u-button type="primary" text="保存" @click="saveHandle" />
			<u-button type="error" plain text="注销账户" @click="userDestroy" />
		</view>
		<u-popup :show="show" @close="close" round="12px">
			<view class="select-date-popup">
				<view class="header-btns">
					<view class="cancel-btn" @click="close">
						<text>取消</text>
					</view>
					<view class="confirm-btn" @click="selectDateConfirm">
						<text>确定</text>
					</view>
				</view>
				<picker-view :indicator-style="indicatorStyle" :value="value" @change="bindChange"
					class="picker-view box">
					<picker-view-column>
						<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
					</picker-view-column>
				</picker-view>
			</view>
		</u-popup>
		<sex-picker @confirm="selectSexConfirm" @close="sexPickerClose" :range="sexRange" :show="showSexPicker" />
		<!-- <u-datetime-picker @confirm="birthConfirm" :show="showDatePicker" v-model="userData.birth" mode="date" /> -->
		<edu-date-picker ref="dateRef" />
	</view>
</template>

<script>
	import { BASE_URL } from '@/constant/index.js'
	import { patchZero, uploadFile } from '@/utils/tool.js'
	import SexPicker from './sex-picker.vue'
	import { mapGetters } from 'vuex'
	export default {
		components: { SexPicker },
		onLoad() {
			uni.$on('editInfo', this.onEditInfo)
		},
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			for (let i = 1990; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			const dateStr = `${year}-${patchZero(month)}-${patchZero(day)}`
			const dayCount = this.getCountDays(dateStr)
			for (let i = 1; i <= dayCount; i++) {
				days.push(i)
			}
			return {
				showDatePicker: false,
				userData: {
					birth: '',
					avatar: '',
					nickname: '',
					mobile: '',
					sex: '',
					sn: '',
					days: '',
					career: '',
					region: '',
					desc: '',
					inviteCode: '',
				},
				title: 'picker-view',
				years,
				months,
				days,
				value: [year - 1990, month - 1, day - 1],
				visible: true,
				indicatorStyle: `height: 50px;`,
				show: false,
				dateValue: `${year}-${patchZero(month)}-${patchZero(day)}`,
				sexRange: ['男', '女'],
				showSexPicker: false,
				hasInit: false,
				showRegin: false,
				hasAuthorization: false,
			};
		},
		onShow() {
			if (this.hasInit) return
			this.hasInit = true
			console.log(this.userInfo, 'userInfo');
			const { avatar, nickname, sex, account, mobile, introduce, sn, birth } = this.userInfo
			const sexEnum = {
				1: '男',
				2: '女'
			}
			this.userData = {
				birth,
				avatar,
				nickname,
				sex: sexEnum[sex] || '未知',
				sn: account,
				mobile,
				desc: introduce || '',
				inviteCode: sn
			}
		},
		methods: {
			async selectBirth() {
				const [cancel, result] = await this.$refs.dateRef.open(this.userData.birth)
				if (cancel) return
				this.userData.birth = result
			},
			async confirmDestroy() {
				const resp = await this.$request({
					url: "/index/userUnsubscribe",
				})
				const { code, msg } = resp
				this.$toast({ title: msg }, async () => {
					if (!code) return
					await this.$store.dispatch('logout')
					uni.reLaunch({
						url: '/pages/login/login'
					})
				})
			},
			userDestroy() {
				uni.showModal({
					title: '警告',
					content: '您确定要注销当前账号吗?',
					confirmText: '注销',
					success: ev => {
						if (ev.cancel) return
						this.confirmDestroy()
					}
				})
			},
			chooseReginConfirm(v) {
				const { value, code } = v
				this.userData.region = value
				this.userData.reginCode = code
				this.showRegin = false
			},
			async saveHandle() {
				uni.showLoading({
					title: "正在保存",
					mask: true
				})
				const { userData } = this
				const { nickname, avatar, desc: introduce, mobile, birth } = userData
				const resp = await this.$request({
					url: "/login/updateUser",
					data: { nickname, avatar, introduce, mobile, birth },
				})
				await this.$delay(300)
				const { code, msg } = resp
				uni.hideLoading()
				if (code !== 1) return this.$toast({ title: msg })
				this.$toast({ title: '修改成功' })
				this.$store.dispatch('getUserinfo')
			},
			async saveConfirm() {
				uni.showLoading({
					title: "正在保存",
					mask: true
				})
				const { userData } = this
				const { sex, reginCode } = userData
				let sexValue = 0
				if (sex === '男') {
					sexValue = 1
				}
				if (sex === "女") {
					sexValue = 2
				}
				const payload = {
					...userData,
					sex: sexValue
				}
				if (reginCode) {
					payload.regin = reginCode
				}
				const resp = await this.$request({
					url: "/login/updateUser",
					data: payload,
				})
				await this.$delay(300)
				const { code, msg } = resp
				uni.hideLoading()
				if (code !== 1) return this.$toast({ title: msg })
				this.$toast({ title: '修改成功' })
				this.$store.dispatch('getUserinfo')
			},
			async uploadImage(path) {
				const [error, resp] = await uploadFile(path)
				if (error) return
				console.log(resp, 'resp');
				const { uri } = resp
				this.userData.avatar = uri
			},
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: ev => {
						const { tempFilePaths } = ev
						if (!tempFilePaths.length) return
						this.uploadImage(tempFilePaths[0])
					}
				})
			},
			onEditInfo({ type, value }) {
				const keyEnum = {
					job: 'career',
					address: 'region',
					desc: 'desc',
					nickname: 'nickname',
					mobile: 'mobile',
				}
				if (!keyEnum.hasOwnProperty(type)) return
				const targetKey = keyEnum[type]
				this.userData[targetKey] = value
			},
			toEditDesc(type) {
				if (type === 'mobile') return
				const value = this.userData[type]
				uni.navigateTo({
					url: '/pages-bundle/userinfo/edit-desc?type=' + type,
					success: ev => {
						console.log(this.userData, 'userData');
						ev.eventChannel.emit('onEdit', { type, value })
					}
				})
			},
			selectSexConfirm(v) {
				this.userData.sex = v
				this.showSexPicker = false
			},
			sexPickerClose() {
				this.showSexPicker = false
			},
			selectDateConfirm() {
				setTimeout(() => {
					const { dateValue } = this
					this.userData.birthday = dateValue
					this.close()
				})
			},
			close() {
				this.show = false
			},
			getCountDays(dateStr) {
				const curDate = new Date(dateStr);
				const curMonth = curDate.getMonth();
				curDate.setMonth(curMonth + 1);
				curDate.setDate(0);
				return curDate.getDate();
			},
			bindChange(e) {
				const [y, m, d] = e.detail.value
				const { years, months, days } = this
				const [year, month, day] = [years[y], months[m], days[d]]
				const dateStr = `${year}/${patchZero(month)}/1`
				const dayCount = this.getCountDays(dateStr)
				const _days = []
				for (let i = 1; i <= dayCount; i++) {
					_days.push(i)
				}
				this.days = _days
				this.dateValue = `${year}-${patchZero(month)}-${patchZero(day)}`
				const yearIndex = years.findIndex(item => item === year)
				console.log(yearIndex, 'yearIndex');
				this.value = [yearIndex, month - 1, day - 1]
			},
			selectDateChange(ev) {
				const { value } = ev.detail
			}
		},
		computed: {
			...mapGetters(['userInfo'])
		},
	}
</script>

<style lang="scss" scoped>
	.edit-userinfo-wrap {
		background: $bg-color;
		padding-top: 24rpx;

		.footer-btn-wrp {
			padding: 32rpx;
			box-sizing: border-box;
			display: flex;
			flex-flow: column;
			gap: 32rpx;
		}

		.select-date-popup {

			.header-btns {
				display: flex;
				justify-content: space-between;
				padding: 24rpx 32rpx;
				box-sizing: border-box;
				font-size: 26rpx;
				align-items: center;

				.cancel-btn {
					color: rgb(25, 25, 25);
				}

				.confirm-btn {
					color: #FFF;
					padding: 12rpx 24rpx;
					border-radius: 32rpx;
					background: rgb(35, 121, 255);

				}
			}

			.picker-view {
				width: 750rpx;
				height: 600rpx;
			}

			.item {
				line-height: 100rpx;
				text-align: center;
			}
		}



		.cell-group {
			box-sizing: border-box;
			position: relative;
			background-color: #FFF;
			margin-bottom: 24rpx;

			.cell-item {
				display: flex;
				align-items: center;
				padding: 32rpx;
				box-sizing: border-box;
				position: relative;

				&:last-child {
					&::after {
						background-color: #FFF;
					}
				}

				&::after {
					content: "";
					display: block;
					position: absolute;
					left: 32rpx;
					right: 32rpx;
					bottom: 0;
					height: 1px;
					background-color: #eeeeee;
				}

				.lcell-item-label {
					color: #1b1b1b;
					font-size: 30rpx;
				}

				.cell-content {
					margin-left: auto;
					display: flex;
					align-items: center;
					color: #9c9c9c;

					.cell-content-text {
						&.item-desc {
							width: 200rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							text-align: right;
						}
					}

					.chevron {
						width: 32rpx;
						height: 32rpx;
						margin-left: 12rpx;
					}

					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
					}
				}
			}
		}
	}
</style>